package com.cwf.business.util;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.hardware.Camera;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.cwf.business.MyApplication;

import java.io.IOException;
import java.net.NetworkInterface;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Created by sam_chan on 2017/5/8.
 */
public class MainUtil {

    public static String statusBarColor = "#3F51B5";

    public static void setStatusBarColor(Activity activity, int color) {
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams localLayoutParams = activity.getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
            optionStatusBar(activity);
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (DFStatusBar.canModifyStatusBar(activity.getWindow())) {
                WindowManager.LayoutParams localLayoutParams = activity.getWindow().getAttributes();
                localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
                optionStatusBar(activity);
                return;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                activity.getWindow().setStatusBarColor(color);
                return;
            }

            activity.getWindow().setStatusBarColor(color);
        }
    }

    /**
     * 不需要处理状态栏，please return false.
     * 需要对状态栏进行处理：return DFStatusBar.setDarkStatusBar() or DFStatusBar.setLightStatusBar();
     */
    protected static boolean optionStatusBar(Activity activity) {
        return DFStatusBar.setLightStatusBar(activity);
    }

    protected static int statusBarColor() {
        return Color.parseColor(statusBarColor);
    }

    public static int dipToPx(float dpValue) {
        final float scale = MyApplication.getContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int pxToDip(float pxValue) {
        final float scale = MyApplication.getContext().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static <E> boolean isEmptyList(Collection<E> list) {
        return list == null || list.size() == 0;
    }

    public static <E> boolean nonEmptyList(Collection<E> list) {
        if (list == null || list.size() == 0) {
            return false;
        }
        return true;
    }

    /**
     * 获取状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 检查当前网络是否可用
     *
     * @param context
     */
    public static boolean isNetworkAvailable(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()) {
                NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if (wifiNetworkInfo.isConnected()) {
                    if ("0".equals(Test.execute("/system/bin/ping -c 1 -w 1 www.baidu.com").get(0))) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }
            } else {
                return false;
            }
        }
    }

    /**
     * 获取底部导航栏的高度(有些手机底部是虚拟按键，适配部分机型时需要减去这部分的高度)
     */
    public static Point getNavigationBarSize(Context context) {
        Point appUsableSize = getAppUsableScreenSize(context);
        Point realScreenSize = getRealScreenSize(context);

        // navigation bar on the right
        if (appUsableSize.x < realScreenSize.x) {
            return new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y);
        }

        // navigation bar at the bottom
        if (appUsableSize.y < realScreenSize.y) {
            return new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y);
        }

        // navigation bar is not present
        return new Point();
    }

    /**
     * 获取 APP 可用的屏幕尺寸大小，不包括底部导航栏
     */
    public static Point getAppUsableScreenSize(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size;
    }

    /**
     * 获取 APP 整个屏幕的大小，包括底部导航栏
     */
    public static Point getRealScreenSize(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        Point size = new Point();

        if (Build.VERSION.SDK_INT >= 17) {
            display.getRealSize(size);
        } else if (Build.VERSION.SDK_INT >= 14) {
            try {
                size.x = (Integer) Display.class.getMethod("getRawWidth").invoke(display);
                size.y = (Integer) Display.class.getMethod("getRawHeight").invoke(display);
            } catch (Exception ignored) {

            }
        }

        return size;
    }


    public static int parseInt(String str) {
        try {
            return Integer.parseInt(str);
        } catch (Exception ex) {
            return 0;
        }
    }

    /**
     * 尝试关闭软键盘
     */
    public static void closeKeyBoardWhenNeed(final Activity activity) {
        View currentFocus = activity.getCurrentFocus();
        if (currentFocus != null) {
            MainUtil.isInputMethodShow(false, currentFocus);
        }
    }

    /***
     * 判断是否有外网连接（普通方法不能判断外网的网络是否连接，比如连接上局域网）
     */
    public static boolean ping() {
        try {
            final String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
            final Process p = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 8 " + ip);// ping网址,8S没响应
            // ping的状态
            final int status = p.waitFor();
            if (status == 0) {
                return true;
            }
        } catch (final IOException e) {
            e.printStackTrace();
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String getWifiDeviceAddress() {
        try {
            String interfaceName = "wlan0";
            List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface intf : interfaces) {
                if (!intf.getName().equalsIgnoreCase(interfaceName)) {
                    continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if (mac == null) {
                    return "";
                }
                StringBuilder buf = new StringBuilder();
                for (byte aMac : mac) {
                    buf.append(String.format("%02X:", aMac));
                }
                if (buf.length() > 0) {
                    buf.deleteCharAt(buf.length() - 1);
                }
                return buf.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static int getScreenWidth() {
        return MyApplication.getContext().getResources().getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight() {
        return MyApplication.getContext().getResources().getDisplayMetrics().heightPixels;
    }

    public static boolean isWifi() {
        ConnectivityManager connectMgr = (ConnectivityManager) MyApplication.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectMgr.getActiveNetworkInfo();
        return info != null && info.getType() == ConnectivityManager.TYPE_WIFI;
    }

    public static void isInputMethodShow(boolean isInputShow, View view) {
        InputMethodManager imm = (InputMethodManager) MyApplication.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isInputShow) {
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//只有使用这个现实之后才能正常的隐藏键盘
        } else {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
        }
    }

    public static Bitmap scaleBitmap(Resources resources, int resId, int requestWidth, int requestHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(resources, resId, options);

        int realWidth = options.outWidth;
        int realHeight = options.outHeight;
        int inSampleSize = 1;

        if (realWidth > requestWidth || realHeight > requestHeight) {
            int halfWidth = requestWidth / 2;
            int halfHeight = requestHeight / 2;
            while ((halfWidth / inSampleSize) > requestWidth
                    && (halfHeight / inSampleSize) > requestHeight) {
                inSampleSize *= 2;
            }
        }

        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;
        return BitmapFactory.decodeResource(resources, resId, options);
    }

    public static int parsetInt(String number) {
        int num;
        try {
            num = Integer.parseInt(number);
        } catch (Exception ex) {
            num = 0;
        }
        return num;
    }

    public static boolean isCameraCanUsed(Context context) {
        boolean isCameraCanUsed = false;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            isCameraCanUsed = true;
        } catch (Exception e) {
            isCameraCanUsed = false;
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                isCameraCanUsed = true;
            }
        }
        return isCameraCanUsed;
    }

    public static String listStringToString(List<String> strings) {
        if (MainUtil.isEmptyList(strings)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (String string : strings)
            sb.append(string).append(" ");
        return sb.toString();
    }

    public static String toString(Object object) {
        if (object == null) {
            return "Null Object.";
        }
        return object.toString();
    }


}
